<?php

class robokassa extends PaymentModule
{
    private $_html = '';
    private $_postErrors = array();

    public function __construct()
    {
        $this->name = 'robokassa';        
        $this->tab = 'Payment';
        $this->version = 1.0;
        
        $this->currencies = true;
        $this->currencies_mode = 'radio';
        
        $config = Configuration::getMultiple(array('RB_MERCHANT_LOGIN', 'RB_PASSWORD1', 'RB_PASSWORD2'));    
        if (isset($config['RB_MERCHANT_LOGIN']))
            $this->rb_merchant_login = $config['RB_MERCHANT_LOGIN'];
	if (isset($config['RB_PASSWORD1']))
            $this->rb_password1 = $config['RB_PASSWORD1'];
	if (isset($config['RB_PASSWORD2']))
            $this->rb_password2 = $config['RB_PASSWORD2'];
            
        parent::__construct();
        
        /* The parent construct is required for translations */
        $this->page = basename(__FILE__, '.php');
        $this->displayName = 'RoboKassa';
        $this->description = $this->l('Accept payments with RoboKassa');
        $this->confirmUninstall = $this->l('Are you sure you want to delete your details ?');
        
        if (!isset($this->rb_merchant_login))
            $this->warning = $this->l('Your RoboKassa account must be set correctly (set merchant login)');
    }        

    function install()
    {        
        if (!parent::install() OR !$this->registerHook('payment') OR !$this->registerHook('paymentReturn'))
            return false;
        return true;
    }
    
    function uninstall()
    {
        if (!Configuration::deleteByName('RB_MERCHANT_LOGIN') OR !parent::uninstall())
            return false;
        return true;
    }
    
    private function _postValidation()
    {
        if (isset($_POST['btnSubmit']))
        {
            if (empty($_POST['rb_merchant_login']))
                $this->_postErrors[] = $this->l('Merchant Login is required');
            elseif (empty($_POST['rb_password1']))
                $this->_postErrors[] = $this->l('Robokassa password1 is required');
            elseif (empty($_POST['rb_password2']))
                $this->_postErrors[] = $this->l('Robokassa password2 is required');
        }
    }

    private function _postProcess()
    {
        if (isset($_POST['btnSubmit']))
        {
            Configuration::updateValue('RB_MERCHANT_LOGIN', $_POST['rb_merchant_login']);
            Configuration::updateValue('RB_PASSWORD1', $_POST['rb_password1']);
            Configuration::updateValue('RB_PASSWORD2', $_POST['rb_password2']);
        }
        $this->_html .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="'.$this->l('OK').'" /> '.$this->l('Settings updated').'</div>';
    }
    
    private function _displayRb()
    {
        $this->_html .= '<img src="../modules/robokassa/robokassa.png" style="float:left; margin-right:15px;"><b>'.$this->l('This module allows you to accept payments by RoboKassa.').'</b><br /><br />
        '.$this->l('You need to register on the site').' <a href="https://robokassa.ru" target="blank">robokassa.ru</a> <br /><br /><br />';
    }
    
    private function _displayForm()
    {
        $this->_html .=
        '<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
            <fieldset>
            <legend><img src="../img/admin/contact.gif" />'.$this->l('Contact details').'</legend>
                <table border="0" width="500" cellpadding="0" cellspacing="0" id="form">
                    <tr><td colspan="2">'.$this->l('Please specify required data').'.<br /><br /></td></tr>
                    <tr><td width="140" style="height: 35px;">'.$this->l('RoboKassa Merchant Login').'</td><td><input type="text" name="rb_merchant_login" value="'.htmlentities(Tools::getValue('rb_merchant_login', $this->rb_merchant_login), ENT_COMPAT, 'UTF-8').'" style="width: 300px;" /></td></tr>
                    <tr><td width="140" style="height: 35px;">'.$this->l('RoboKassa Password1').'</td><td><input type="text" name="rb_password1" value="'.htmlentities(Tools::getValue('rb_password1', $this->rb_password1), ENT_COMPAT, 'UTF-8').'" style="width: 300px;" /></td></tr>
                    <tr><td width="140" style="height: 35px;">'.$this->l('RoboKassa Password2').'</td><td><input type="text" name="rb_password2" value="'.htmlentities(Tools::getValue('rb_password2', $this->rb_password2), ENT_COMPAT, 'UTF-8').'" style="width: 300px;" /></td></tr>
                    <tr><td colspan="2" align="center"><br /><input class="button" name="btnSubmit" value="'.$this->l('Update settings').'" type="submit" /></td></tr>
                </table>
            </fieldset>
        </form>';
    }

    function getContent()
    {
        $this->_html = '<h2>'.$this->displayName.'</h2>';

        if (!empty($_POST))
        {
            $this->_postValidation();
            if (!sizeof($this->_postErrors))
                $this->_postProcess();
            else
                foreach ($this->_postErrors AS $err)
                    $this->_html .= '<div class="alert error">'. $err .'</div>';
        }
        else
            $this->_html .= '<br />';

        $this->_displayRb();
        $this->_displayForm();

        return $this->_html;
    }

    function hookPayment($params)
    {
        global $smarty;
        
        $delivery = new Address(intval($params['cart']->id_address_delivery));
        $invoice = new Address(intval($params['cart']->id_address_invoice));
        $customer = new Customer(intval($params['cart']->id_customer));                
                
        $currency      = $this->getCurrency();
        $amount        = number_format(Tools::convertPrice($params['cart']->getOrderTotal(true, 3), $currency), 2, '.', '');
        $order_id      = $params['cart']->id;
        $description   = 'Оплата товаров на сайте '.$_SERVER['SERVER_NAME'];               
        $rb_password1    = Configuration::get('RB_PASSWORD1');
        $rb_mrh_login  = Configuration::get('RB_MERCHANT_LOGIN');
        $rb_sign       = md5("$rb_mrh_login:$amount:$order_id:$rb_password1");

                
        $smarty->assign(array( 
            'robokassaUrl'          => 'https://merchant.roboxchange.com/Index.aspx',
            //'robokassaUrl'          => 'http://test.robokassa.ru/Index.aspx',
            'rb_payment_amount'     => $amount,
            'rb_payment_id'         => $order_id,
            'rb_payment_desc'       => $description,
            'rb_mrh_login'          => $rb_mrh_login,
            'rb_sign'               => $rb_sign,
            'this_path'             => $this->_path,
            'this_path_ssl'         => Configuration::get('PS_FO_PROTOCOL').$_SERVER['HTTP_HOST'].__PS_BASE_URI__."modules/{$this->name}/"));

        return $this->display(__FILE__, 'payment.tpl');
    }
    
    public function getL($key)
    {
        $translations = array(
            'success'=> 'Robokassa transaction is carried out successfully.',
            'fail'=> 'Robokassa transaction is refused.'
        );
        return $translations[$key];
    }

    public function hookPaymentReturn($params)
    {
        if (!$this->active)
            return ;

        return $this->display(__FILE__, 'payment_return.tpl');
    }
    
}

?>
